//
//  XMLComposePictureView.swift
//  Weibo
//
//  Created by mac on 16/5/20.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let collectionViewCellReuseIdentifier = "collectionViewCellReuseIdentifier"

class XMLComposePictureView: UICollectionView,UICollectionViewDataSource {
    
   private lazy var images :[UIImage] = [UIImage]()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        backgroundColor = UIColor.whiteColor()
        dataSource = self
        
        registerClass(XMLComposeCollectionViewCell.self, forCellWithReuseIdentifier: collectionViewCellReuseIdentifier)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //  每项间距
        let itemMargin: CGFloat = 5
        //  计算每项宽度
        let itemWidth = (frame.size.width - 2 * itemMargin) / 3
        //  获取布局对象
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        //  设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //  设置间距
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
    }
    
    func addImage(image :UIImage) {
    
        images.append(image)
        reloadData()
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return images.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewCellReuseIdentifier, forIndexPath: indexPath) as! XMLComposeCollectionViewCell
//        cell.backgroundColor = RandomColor()
        
        cell.imageView.image = images[indexPath.row]
        return cell
    }
}
